<?php


namespace Modules\Admin\Services;


use App\Models\User;
use App\Services\BaseService;
use Illuminate\Support\Facades\DB;
use Modules\Admin\Entities\Admin;
use Modules\Admin\Entities\Role;

class RoleService extends BaseService
{
    /**
     * 添加角色
     *
     * @param array $data
     *
     * @return Role
     */
    public function Add(array $data): Role
    {
        $data = collect($data);
        return DB::transaction(function () use ($data) {
            $permissions = $data->get('permissions');
            $role = Role::create($data->except('permissions')->toArray());

            $permissions = PermissionService::mergePermissionAncestors($permissions);
            $role->givePermissionTo($permissions);
            return $role;
        });
    }

    public function Update(Role $role, array $data): Role
    {
        $data = collect($data);
        return DB::transaction(function () use ($role, $data) {
            $permissions = $data->get('permissions');
            $role->update($data->except('permissions')->toArray());
            // syncPermissions 同步权限 可以撤消或新增权限【更新时 取消勾选的权限会被撤消 新勾选的权限会被新增】
            $permissions = PermissionService::mergePermissionAncestors($permissions);
            $role->syncPermissions($permissions);
            return $role;
        });
    }

    public function Destroy(Role $role)
    {
        $role->syncPermissions([]); // 撤消该角色的所有权限
        $role->delete();
    }
}
